package com.corn.juc.bq;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2020/12/31 16:08
 */

public class BlockQueueDemo {

    public static void main(String[] args) throws Exception {
//        testThrowOperation();
//        testReturnBoolean();
//        testTimeout();
//        testBlock();
        testCheckHead();
    }

    /**
     * add remove 队列满或者空抛出异常
     * IllegalStateException: Queue full
     * NoSuchElementException
     */
    public static void testThrowOperation() {
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2);
        queue.add(1);
        queue.add(1);
//        queue.add(1); // IllegalStateException: Queue full
        queue.remove();
        queue.remove();
//        queue.remove(); //NoSuchElementException
    }

    /**
     * 返回boolean 组
     * offer 如果插入成功返回true 否则false
     * poll 获取元素 有返回 没有返回null
     */
    public static void testReturnBoolean() {
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2);
        System.out.println(queue.offer(1));
        System.out.println(queue.offer(1));
        System.out.println(queue.offer(1));
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
    }

    /**
     * 带超时的 offer 和 poll 操作
     *
     * @throws InterruptedException
     */
    public static void testTimeout() throws InterruptedException {
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2);

        System.out.println(queue.offer(1, 1, TimeUnit.SECONDS));
        System.out.println(queue.offer(1, 1, TimeUnit.SECONDS));
        System.out.println(queue.offer(1, 3, TimeUnit.SECONDS));

        System.out.println(queue.poll(1, TimeUnit.SECONDS));
        System.out.println(queue.poll(1, TimeUnit.SECONDS));
        System.out.println(queue.poll(3, TimeUnit.SECONDS));
    }

    /**
     * put 队列满的时候阻塞等待消费之后再次插入
     * take 队列空的时候阻塞等待队列有数据
     *
     * @throws InterruptedException
     */
    public static void testBlock() throws InterruptedException {
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2);
        queue.put(1);
        queue.put(1);
//        queue.put(1); // 阻塞
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());// 阻塞
    }

    /**
     * peek查看头元素 没有返回null
     * element 查看头元素 没有抛 NoSuchElementException
     */
    public static void testCheckHead() {
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2);
        System.out.println(queue.peek());
        System.out.println(queue.element());
    }
}
